import 'package:flutter/material.dart';
import '../../api/api_service.dart';
import '../../provide/userProvide.dart';
import '../../routers/application.dart';
import 'package:provide/provide.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  TextEditingController _bikeName = TextEditingController();
  List bikeList = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
      appBar: AppBar(
        title: Text('搜索'),
      ),
      body: ListView(
        padding: EdgeInsets.only(left: 30.0, right: 30.0),
        children: <Widget>[_searchInkWel(), _leftInkWel()],
      ),
    );
  }

  Widget _searchInkWel() {
    return Container(
        child: Row(
      children: <Widget>[
        Expanded(
          child: TextField(
              keyboardType: TextInputType.emailAddress,
              autofocus: false,
              controller: _bikeName,
              decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(5.0),
                  hintText: '请输入自行车编号',
                  labelText: "请输入账号")),
        ),
        FlatButton(
          child: Text(
            '搜索',
            style: TextStyle(color: Color.fromRGBO(255, 170, 13, 1)),
          ),
          onPressed: () {
            _searchData();
            // Navigator.pushNamed(context, "/register");
            // Application.router.navigateTo.(context,"/register",transition: TransitionType.inFromRight);
          },
        )
      ],
    ));
  }

  Widget _leftInkWel() {
    return Column(
      children: <Widget>[
        ListView.builder(
          itemCount: bikeList.length,
          shrinkWrap: true,
          itemBuilder: (context, index) {
            return _pageList(index);
          },
        )
      ],
    );
    // return InkWell(
    //     child: ;
  }

  Widget _pageList(int index) {
    return InkWell(
        child: Card(
      margin: EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          ListTile(
            title:
                Text(bikeList[index]['name'], style: TextStyle(fontSize: 28)),
            subtitle: Text("编号"),
          ),
          Divider(),
          ListTile(
            title: Text("价格     ${bikeList[index]['money']}/小时"),
          ),
          ListTile(
            title:
                Text("状态:   ${bikeList[index]['state'] == true ? '正常' : '异常'}"),
          ),
          FlatButton(
            color: Colors.pink,
            child: Text(
              '租用',
              style:
                  TextStyle(color: Colors.white, backgroundColor: Colors.pink),
            ),
            onPressed: () {
              _postRentData(bikeList[index]['_id']);
            },
          )
        ],
      ),
    ));
  }

  _postRentData(id) async {
    try {
      var userInfo = Provide.value<UserProvide>(context).userIofo;

      if (userInfo == null) {
        Application.router.navigateTo(context, "/login");
        return;
      }
      await rentBike({"bike_id": id, "user_id": userInfo.id}).then((data) {
        showDialog(
            context: context,
            builder: (_) => new AlertDialog(content: new Text(data['msg'])));
        if (data['success']) {
          setState(() {
            bikeList = [];
          });
        }
      });
    } catch (e) {
      print('登录异常');
      print(e);
    }
  }

// 搜索
  _searchData() async {
    try {
      // var userInfo = Provide.value<UserProvide>(context).userIofo;

      // if (userInfo == null) {
      //   Application.router.navigateTo(context, "/login");
      //   return;
      // }
      print(_bikeName);
      await searchRentApi(_bikeName.text.toString().trim()).then((data) {
        if (data['success']) {
          setState(() {
            bikeList = data['result'];
          });
        } else {
          showDialog(
              context: context,
              builder: (_) => new AlertDialog(content: new Text(data['msg'])));
        }

        // print(data);
        // showDialog(
        //     context: context,
        //     builder: (_) => new AlertDialog(content: new Text(data['msg'])));
        // if (data['success']) {
        //   print("租车成功");
        // }
      });
    } catch (e) {
      print('登录异常');
      print(e);
    }
  }
}
